/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hiof.moraa.server.service;

import com.hiof.moraa.mapping.TblAthlete;
import com.hiof.moraa.mapping.TblSupport;
import com.hiof.moraa.mapping.TblTeam;
import com.hiof.moraa.mapping.TblUser;
import com.hiof.moraa.server.dao.TeamDAO;
import com.hiof.moraa.server.dao.UserDAO;
import com.hiof.moraa.server.service.model.TypeOfAttendant;
import com.hiof.moraa.server.service.model.LoginStatus;
import com.hiof.moraa.server.service.model.UserInfo;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.Iterator;

/**
 * @author Bergy
 */
@Transactional(propagation = Propagation.REQUIRED)
public class UserService {

    UserDAO userDAO;
    TeamDAO teamDAO;
    EncryptService encryptService;

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void setTeamDAO(TeamDAO teamDAO) {
        this.teamDAO = teamDAO;
    }

    public void setEncryptService(EncryptService encryptService) {
        this.encryptService = encryptService;
    }
    public UserInfo getUserInfoByUserIdAndRouteId(int userId, int routeId) {
        UserInfo userInfo = userDAO.getUserInfoFromUserId(userId);
        if (userInfo != null) {
            TblTeam team = teamDAO.getTeamFromUserIdAndRouteID(userId, routeId);
            return createTeammeberList(team, userId, userInfo);
        } else {
            return new UserInfo();
        }
    }

    public UserInfo getUserInfoByUsernameAndRouteId(String username, int routeId) {
        UserInfo userInfo = userDAO.getUserInfoFromUsername(username);
        if (userInfo != null) {
            TblTeam team = teamDAO.getTeamFromUsernameAndRouteID(username, routeId);
            return createTeammeberList(team, userInfo.getUserId(), userInfo);
        } else {
            return new UserInfo();
        }
    }

    private UserInfo createTeammeberList(TblTeam team, int userId, UserInfo userInfo) {
        for (Iterator obj = team.getTblAthletes().iterator(); obj.hasNext(); ) {
            TblAthlete athlete = (TblAthlete) obj.next();
            TblUser user = athlete.getTblUser();
            if (user.getId() != userId) {
                UserInfo teammate = new UserInfo(user.getId(), user.getUsername(), user.getFirstName() + " " + user.getLastName(), user.getProfilePicture(), user.getPhone(), user.getAge(), user.getMaxHeartRate());
                teammate.setAttendantId(athlete.getId());
                teammate.setAttendantCode(athlete.getAttendantCode());
                teammate.setTypeOfAttendant(TypeOfAttendant.ATHLETE);
                userInfo.addMember(teammate);
            } else {
                userInfo.setTypeOfAttendant(TypeOfAttendant.ATHLETE);
                userInfo.setAttendantId(athlete.getId());
                userInfo.setAttendantCode(athlete.getAttendantCode());
            }
        }
        for (Iterator obj = team.getTblSupports().iterator(); obj.hasNext(); ) {
            TblSupport support = (TblSupport) obj.next();
            TblUser user = support.getTblUser();
            if (user.getId() != userId) {
                UserInfo teammate = new UserInfo(user.getId(), user.getUsername(), user.getFirstName() + " " + user.getLastName(), user.getProfilePicture(), user.getPhone(), user.getAge(), user.getMaxHeartRate());
                teammate.setTypeOfAttendant(TypeOfAttendant.SUPPORT);
                teammate.setAttendantId(support.getId());
                teammate.setAttendantCode(support.getAttendantCode());
                userInfo.addMember(teammate);
            } else {
                userInfo.setTypeOfAttendant(TypeOfAttendant.SUPPORT);
                userInfo.setAttendantId(support.getId());
                userInfo.setAttendantCode(support.getAttendantCode());
            }
        }
        Collections.sort(userInfo.getTeamMembers());
        return userInfo;
    }

    public LoginStatus login(String userName, String password) {
        TblUser user = userDAO.getTbleUserFromUsername(userName);
        String encryptedPassword = null;
        try {
            encryptedPassword = encryptService.encrypt(password);
        } catch (NoSuchAlgorithmException e) {
            return LoginStatus.UsernamePasswordNotMatch;
        }
        if (user != null) {
            if (user.getPassword().equals(encryptedPassword)) {
                return LoginStatus.OK;
            } else {
                return LoginStatus.UsernamePasswordNotMatch;
            }
        } else {
            return LoginStatus.UserNotExist;
        }
    }

    private String encrypt(String password) throws NoSuchAlgorithmException {
        MessageDigest algorithm = MessageDigest.getInstance("MD5");
        algorithm .reset();
        byte messageDigest[] = algorithm.digest();

        StringBuffer hexString = new StringBuffer();
        for (int i=0;i<messageDigest.length;i++) {
            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
        }
        return hexString.toString();
    }
}
